<?php

declare(strict_types=1);

namespace App\Middleware\Business;

use App\Exception\BusinessException;
use App\Kernel\Util\UserJwtInstance;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class BusinessMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $user = UserJwtInstance::instance()->build()->getUser();

        // 登录账户用户组是否为商家
        if ($user->group_id !== 3) {
            throw new BusinessException(401, __('api.USER.STATUS_EXCEPTION'));
        }

        $business = $user->business;

        // 商家是否存在
        if (!$business) {
            throw new BusinessException(401, __('api.BUSINESS.NOT_EXIST'));
        }

        // 商家是否被禁用
        if ($business->status === 0) {
            throw new BusinessException(401, __('api.BUSINESS.BUSINESS_BANNED'));
        }

        // 商家是否通过审核
        if ($business->status != 1) {
            throw new BusinessException(401, __('api.BUSINESS.NOT_PASS_CERT'));
        }

        return $handler->handle($request);
    }
}